document.addEventListener('DOMContentLoaded', () => {
    const redirectsDiv = document.getElementById('redirects');
    const addRedirectButton = document.getElementById('addRedirect');
    const saveButton = document.getElementById('save');
    const enableRedirectsCheckbox = document.getElementById('enableRedirects');

    chrome.storage.sync.get(['redirects', 'enableRedirects'], (data) => {
        const redirects = data.redirects || [];
        const enableRedirects = data.enableRedirects || false;
        enableRedirectsCheckbox.checked = enableRedirects;
        redirects.forEach((redirect, index) => {
            addRedirectInput(redirect.from, redirect.to, redirect.enabled, index);
        });
    });

    addRedirectButton.addEventListener('click', () => {
        addRedirectInput('', '', true, redirectsDiv.children.length);
    });

    saveButton.addEventListener('click', () => {
        const redirects = [];
        for (let i = 0; i < redirectsDiv.children.length; i++) {
            const from = document.getElementById(`from${i}`).value;
            const to = document.getElementById(`to${i}`).value;
            const enabled = document.getElementById(`enabled${i}`).checked;
            redirects.push({ from, to, enabled });
        }
        const enableRedirects = enableRedirectsCheckbox.checked;
        chrome.storage.sync.set({ redirects, enableRedirects }, () => {
            alert('Settings saved');
        });
    });

    function addRedirectInput(from, to, enabled, index) {
        const div = document.createElement('div');
        div.className = 'redirect';
        div.innerHTML = `
            <input type="text" id="from${index}" placeholder="From URL" value="${from}">
            <input type="text" id="to${index}" placeholder="To URL" value="${to}">
            <label>
                <input type="checkbox" id="enabled${index}" ${enabled ? 'checked' : ''}> Enable
            </label>
        `;
        redirectsDiv.appendChild(div);
    }
});